<template>
  <div>
  	<el-dialog title="修改商品信息" :visible.sync="editorVisible" width="30%" :before-close="closeEditorGoods" @open="opendEnd">
  		<el-form :model="goodsList" ref="editorClassify" label-width="100px">
        <el-form-item label="商品名称" prop="goodsName" :rules="[
              { required: true, message: '请输入商品名称', trigger: 'blur' },
            ]">
        	<el-input type="text" v-model="goodsList.goodsName" placeholder="请输入商品名称"></el-input>
        </el-form-item>

        <el-form-item label="单价" prop="price" :rules="[
              { required: true, message: '请输入单价', trigger: 'blur' },
            ]">
        	<el-input type="text" v-model="goodsList.price" placeholder="请输入单价"></el-input>
        </el-form-item>

        <el-form-item label="规格" prop="specification" :rules="[
              { required: true, message: '请输入规格', trigger: 'blur' },
            ]">
        	<el-input type="text" v-model="goodsList.specification" placeholder="请输入规格"></el-input>
        </el-form-item>

  			<el-form-item label="类型图片" prop="goodsImg">
          <el-input v-show="false" v-model="imgState"/>
          <el-upload
            class="upload-demo"
            ref="upload"
            list-type="picture"
            action=""
            :limit="1"
            :on-change="imgVaildata"
            :auto-upload="false"
            :on-remove="handleRemove"
            :before-upload="beforeUploadHandle"
            :http-request="handleUploadForm"
            >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="隶属分类" prop="classifyId" :rules="[
             { required: true, message: '请选择分类', trigger:'blur'},
           ]">
              <el-select v-model="goodsList.classifyId" placeholder="可选择分类" clearable>
                <el-option
                  v-for="item in classifyOptions"
                  :key="item.classifyId"
                  :label="item.classifyName"
                  :value="item.classifyId"
                  v-if="item.classifyType==0">
                </el-option>
              </el-select>
        </el-form-item>
  		</el-form>
  		<span slot="footer" class="dialog-footer">
  			<el-button @click="closeEditorGoods">取 消</el-button>
  			<el-button type="primary" @click="submitUpload('editorClassify')">确 定</el-button>
  		</span>
  	</el-dialog>
  </div>
</template>

<script>
  export default {
    name: "",
    props: ["editorVisible","editorOptions","editorObj"],
    data() {
    	return {
    		goodsList: {
          goodsName:"",
          price:null,
          specification:null,
          goodsImg:"",
          classifyId:"",
    		},
        classifyOptions:{},
        //判断有无图片
        imgState:null,
        //是否允许执行方法
        goFunction:true,
    	}
    },
    methods: {
      //需要等待dialog 打开完毕后 在金数据渲染
      opendEnd(){
        //设置隶属分类下拉框的值
        this.classifyOptions = this.$props.editorOptions
        //渲染各个框内的数据
        this.goodsList.goodsId = this.$props.editorObj.goodsId
        this.goodsList.goodsName = this.$props.editorObj.goodsName
        this.goodsList.price = this.$props.editorObj.price
        this.goodsList.specification = this.$props.editorObj.specification
        this.goodsList.goodsImg = this.$props.editorObj.goodsImg
        this.goodsList.classifyId = this.$props.editorObj.classify.classifyId
      },
      //设置关闭添加页面方法
      closeEditorGoods() {
          //关闭前还原文本框默认值
          this.clearData()
      		this.$parent.editorVisible = false
      },
      //清除文本框数据，返回相对应文本框的值
      clearData(){
          this.goodsList={
            goodsName:"",
            price:null,
            specification:null,
            goodsImg:"",
            classifyId:"",
          }
          this.clearFiles()
      },
      //清空图片方法
      clearFiles () {
          this.$refs['upload'].clearFiles();
      },
      //判断表单数据是否为空
       //并提交数据
      submitUpload(params) {
        console.log("触发判断事件")
        var self = this
        console.log(self.imgState)
        this.$refs[params].validate((valid) => {
       	if (valid) {
           if(self.imgState==null || self.imgState==""){
             self.editorGoods(params)
             console.log(1)
           }else{
              self.$refs.upload.submit();
             console.log(2)
           }
       	} else {
       		console.log('error submit!!');
       		return false;
       	}
       });
      },
      //验证图片是否为空
      imgVaildata(file, fileList){
        console.log("abbbbbb")
          var self = this
          console.log('vue 图片上传钩子函数')
          self.imgState=file.name
          console.log(self.imgState)
          if(file.name==null || file.name==""){
            self.imgState=null
          }
      },
      //触发删除事件
      handleRemove(file, fileList) {
        console.log("触发删除事件")
        if(file){
          this.imgState=""
        }
        console.log(file, fileList);
      },
      //上传文件前执行的方法,判断文件格式
      beforeUploadHandle(file) {
        console.log("执行上传前方法")
        if (
            file.type !== "image/png" &&
            file.type !== "image/jpeg"
        ) {
          this.$message.error("只支持.jpg、.jpeg、.jpe、.png文件！");
          return false;
        }
      },
      //检查价格和规格是否符合规格
      checkInfo(){
        console.log("执行语法检查")
        let self = this
        //是否允许执行方法
        this.goFunction=true
        /*
            1.检查商品名称是否包含空格
        */
        // 检测输入的数据中是否存在空格
        var goodsName = this.goodsList.goodsName
        if(goodsName.split(" ").length==1){

          /*
              2.检查单价和规格是否是符合规格的
          */
          /* 2.1 判断单价是否符合规格*/
          //进行空值还原，防止数据类型错误
          if(this.goodsList.price===""){
            this.goodsList.price=null
          }
          //判断价格是否为空
          console.log(this.goodsList.price)
          if(this.goodsList.price!=null && self.goFunction){
            //判断是否含有非法字符
            if(String(this.goodsList.price).split(" ").length==1){
              //判断价格是否是符合规格的正数
              var reg = /^\d+(?=\.{0,1}\d+$|$)/
              //判断是否是正数数值型
              if(!reg.test(this.goodsList.price) || Number(this.goodsList.price)===0){
                //不符合规格不允许执行查询方法
                self.goFunction = false
                self.$message({
                  duration: 1500,
                  message: "价格不符合规格!",
                  type: "error",
                  onClose: function() {
                    self.loadStatus = false
                  },
                });
              }
            }else{
              //不符合规格不允许执行查询方法
              self.goFunction = false
              self.$message({
                duration: 1500,
                message: "价格文本框中存在非法字符空格!",
                type: "error",
                onClose: function() {
                  self.goodsList.price = ""
                  self.loadStatus = false
                },
              });
            }
          }
          /* 2.2 判断规格是否符合规格*/
          //进行空值还原，防止数据类型错误
          if(this.goodsList.specification===""){
            this.goodsList.specification=null
          }
          //判断商品规格是否是符合规格的正数
          if(this.goodsList.specification!=null && self.goFunction){
            var speReg = /(^[1-9]\d*$)/
            //判断是否含有非法字符
            if(String(this.goodsList.specification).split(" ").length==1){
              //判断是否是正整数数值型
              if(!speReg.test(this.goodsList.specification) || Number(this.goodsList.specification)===0){
                //不符合规格不允许执行查询方法
                self.goFunction = false
                self.$message({
                  duration: 1500,
                  message: "规格不符合规格!",
                  type: "error",
                  onClose: function() {
                    self.loadStatus = false
                  },
                });
              }
            }else{
              //不符合规格不允许执行查询方法
              self.goFunction = false
              self.$message({
                duration: 1500,
                message: "规格文本框中存在非法字符空格!",
                type: "error",
                onClose: function() {
                  self.goodsList.specification = ""
                  self.loadStatus = false
                },
              });
            }
          }
        }else{
          //不符合规格不允许执行查询方法
          self.goFunction = false
          self.$message({
            duration: 1500,
            message: "用户名中存在非法字符空格!",
            type: "error",
            onClose: function() {
              self.goodsList.goodsName=""
              self.loading = false;
            },
          });
        }
      },

      //执行添加方法(带图片)
      handleUploadForm(param) {
        console.log(param)
        console.log(JSON.stringify(this.goodsList))
        let self = this
        var onlineManager = JSON.parse(sessionStorage.getItem("manager"))
        var page = sessionStorage.getItem("page")
        this.checkInfo()
        //是否允许执行查询方法
        if(self.goFunction){
          let formData = new FormData()
          // 在formData中加入我们需要的参数
          formData.append('file', param.file)
          formData.append('goods', JSON.stringify(this.goodsList))
          console.log("开始向后端发送请求")
          // 向后端发送数据
          self.$http.post('/api/CakeShop/GoodsManage/udpGoodsWithImg', formData).then((res) => {
            console.log(res)
            //判断数据是否存在
            if(res.data.exist===0){
              if (res.data.udpSuccNum>0) {
                self.$message({
                  message: res.data.msg,
                  type: 'success',
                  onClose: function() {
                    //添加完毕后清楚文本框中内容
                    self.clearData()
                    //关闭修改界面
                    self.closeEditorGoods()
                    //添加完数据返回首页
                    self.$parent.getGoodsList(page)
                  }
                });
              }else{
                self.$message({
                  duration: 1500,
                  message: res.data.msg,
                  type: "error",
                  onClose: function() {
                    self.loading = false;
                  },
                });
              }
            }else{
              self.$message({
                duration: 1500,
                message: res.data.msg,
                type: "error",
                onClose: function() {
                  self.loading = false;
                },
              });
            }
          })
        }
      },

      //执行添加方法(不带图片)
      editorGoods(params) {
      	var self = this
      	this.$refs[params].validate((valid) => {
      		if (valid) {
      			var onlineManager = JSON.parse(sessionStorage.getItem("manager"))
            var page = sessionStorage.getItem("page")
            self.checkInfo()
            //是否允许执行查询方法
            if(self.goFunction){
              self.$http({
                url: "/api/CakeShop/GoodsManage/udpGoods",
                method: "post",
                headers: {
                  token: onlineManager.token
                },
                data: {
                  goodsId:self.goodsList.goodsId,
                  goodsName:self.goodsList.goodsName,
                  price:self.goodsList.price,
                  specification:self.goodsList.specification,
                  classifyId: self.goodsList.classifyId,
                },
              }).then(function(res) {
                // console.log(res)
                //判断数据是否存在
                if(res.data.exist===0){
                  if (res.data.udpSuccNum>0) {
                    self.$message({
                      message: res.data.msg,
                      type: 'success',
                      onClose: function() {
                        //添加完毕后清楚文本框中内容
                        self.clearData()
                        //关闭修改界面
                        self.closeEditorGoods()
                        //添加完数据返回首页
                        self.$parent.getGoodsList(page)
                      }
                    });
                  }else{
                    self.$message({
                      duration: 1500,
                      message: res.data.msg,
                      type: "error",
                      onClose: function() {
                        self.loading = false;
                      },
                    });
                  }
                }else{
                  self.$message({
                    duration: 1500,
                    message: res.data.msg,
                    type: "error",
                    onClose: function() {
                      self.loading = false;
                    },
                  });
                }
              })
            }
      		} else {
      			console.log('error submit!!');
      			return false;
      		}
      	});
      }
    },
  }
</script>

<style>
</style>
